package com.huanshi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanshi.common.CommonResult;
import com.huanshi.entity.UmsMember;
import com.huanshi.mapper.UmsMemberMapper;
import com.huanshi.module.ums.param.LoginParam;
import com.huanshi.service.UmsMemberService;
import com.huanshi.utils.BeanCopyUtil;
import com.huanshi.utils.JwtTokenUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author 幻世
 * @since 2023-10-09
 */
@Service
public class UmsMemberServiceImpl extends ServiceImpl<UmsMemberMapper, UmsMember> implements UmsMemberService {

    @Resource
    private UmsMemberMapper memberMapper;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UmsMember findByName(String username) {
        return memberMapper.selectOne(
                new LambdaQueryWrapper<UmsMember>()
                        .eq(UmsMember::getUserName, username)
        );
    }

    @Override
    public CommonResult login(LoginParam loginParam) {
        var user = memberMapper.selectOne(new LambdaQueryWrapper<UmsMember>()
                .eq(UmsMember::getUserName, loginParam.getUserName())
        );
        if (user == null || !passwordEncoder.matches(loginParam.getPassword(), user.getPassword())){
            return CommonResult.failed("用户名或密码不正确！");
        }

        var jwtToken = JwtTokenUtil.createJWT(user.getUserId(), user.getUserName(),new ArrayList<String>());

        return CommonResult.success(jwtToken, "认证成功！");

    }

    @Override
    public UmsMember getUserInfo(String token) {
        Integer userId = JwtTokenUtil.getUserId(token);
        return memberMapper.selectOne(
                new LambdaQueryWrapper<UmsMember>()
                        .eq(UmsMember::getUserId, userId));
    }

    @Override
    public CommonResult register(LoginParam loginParam) {
        var user = memberMapper.selectOne(new LambdaQueryWrapper<UmsMember>()
                .eq(UmsMember::getUserName, loginParam.getUserName())
        );
        if (user != null){
            return CommonResult.failed("该用户名已被注册");
        }
        loginParam.setPassword(passwordEncoder.encode(loginParam.getPassword()));
        UmsMember member = BeanCopyUtil.copyProperties(loginParam, UmsMember.class);
        return CommonResult.success(memberMapper.insert(member));
    }
}
